package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserDAO;
import dao.UserDaoJdbcImpl;
import dao.UserInformationDAO;
import dao.UserInformationDaoJdbcImpl;
import modle.User;
import modle.UserInformation;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/RegisterServlet")
/**
 * 接收注册的用户信息，并写入数据库
 * @author WXE
 *
 */
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    @Override 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		String nickname = request.getParameter("nickname");
		int sex = Integer.parseInt( request.getParameter("sex") );
		UserInformationDAO uid = new UserInformationDaoJdbcImpl();
		UserDAO usd = new UserDaoJdbcImpl();
		User use = new User(account,password);
		response.setContentType("text/html;charset=gb2312"); 
		PrintWriter out = response.getWriter(); 
		System.out.println(use.toString());
		if( usd.writeUser(use) ) {
			UserInformation userInformation = new UserInformation(account, nickname, sex, 0);
			uid.writeUserInformation(userInformation);
			out.println("<html>");  
	        out.print("<script>alert('注册成功！');window.location='Login.jsp';</script>");
	        out.println("<body>");  
	        out.println("</body>");  
	        out.println("</html>");  
	        out.flush();  
		}else {
			out.println("<html>");  
	        out.print("<script>alert('注册失败！该账号已存在');window.location='Register.jsp';</script>");
	        out.println("<body>");  
	        out.println("</body>");  
	        out.println("</html>");  
	        out.flush();  
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
    @Override 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
